package com.winning.common.xmlSchema.schema;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * 类名称：SchemaErrorHandler
 * 类描述：处理在进行Schema校验时产生的异常
 * 校验错误将以如下格式的XML文档定义:
 * <SchemaReport>
 * <warn  line="number"></warn>
 * <error line="number"></error>
 * <fatal line="number"></fatal>
 * </SchemaReport>
 * 创建人：liuwensheng
 * 创建时间：2017-1-12 上午11:10:28
 * 修改人：liuwensheng
 * 修改时间：2017-1-12 上午11:10:28
 * 修改备注：
 */
public class SchemaErrorHandler implements ErrorHandler {

    private Document report = null;
    private Element root = null;

    public SchemaErrorHandler() {
        report = DocumentHelper.createDocument();
        root = DocumentHelper.createElement("SchemaReport");
        report.setRootElement(root);
    }

    public Document getReport() {
        return report;
    }

    public void error(SAXParseException exception) throws SAXException {
        root.add(ExceptionToElement("error", exception));
    }

    public void fatalError(SAXParseException exception) throws SAXException {
        root.add(ExceptionToElement("fatal", exception));
    }

    public void warning(SAXParseException exception) throws SAXException {
        root.add(ExceptionToElement("warn", exception));
    }

    private Element ExceptionToElement(String severity, SAXParseException exception) {

        Element element = DocumentHelper.createElement(severity);

        if (exception.getLineNumber() != 0)
            element.addAttribute("line", Integer.toString(exception.getLineNumber()));

        if (exception.getMessage() != null && exception.getMessage().length() > 0)
            element.addText(exception.getMessage());
        else if (exception.getLocalizedMessage() != null && exception.getLocalizedMessage().length() > 0)
            element.addText(exception.getLocalizedMessage());
        else
            element.addText(exception.getCause().getMessage());

        return element;
    }
}
